
const {pool,execSql}=require('../dbop/mysql')
 // connection.connect();
async function addItem(data){
   //userlist userid  ???
    var  addSql = 'INSERT INTO todolist(id,title,completed) VALUES(?,?,?)';
    var  addSqlParams = [data.id, data.title,data.completed];
    //增
    const result = await execSql(addSql, addSqlParams);
    // const mypromise = new Promise((resolve, reject) => {
    //     pool.getConnection((err, connection) => {
    //         if (err) {
    //             return reject(err);
    //         }
    //         connection.query(addSql, addSqlParams, (err, result) => {
    //             //释放连接
    //             // pool.releaseConnection(connection)
    //             if (err) {
    //                 return reject(err);
    //             }
    //             resolve(result);
    //         });
    // //这么设置，能够解决卡死问题
    //         connection.release();
    //     });
    // });
    return result    

//更新缓存，

    //     ,function (err, result) {
    // connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
    //   if (error) throw error;
    //   console.log('The solution is: ', results[0].solution);
    // });
    
   // connection.end()

}

async function updateItem(data){
    //??  update where id=data.id
 var  updateSql = 'update  todolist  set completed=? where id=?';
    var updateSqlParams = [data.completed,data.id];
    //增
  //  connection.query(updateSql,updateSqlParams)
  const result = await execSql(updateSql, updateSqlParams);
    return 'update ok!!!'


}


async function deleteItem(delid){
    //??  update where id=data.id
    var  delSql = 'delete from todolist where id=?';
    var  delSqlParams = [delid];
    //增
  //  connection.query(delSql,delSqlParams)
  const result = await execSql(delSql, delSqlParams);
    return 'del ok!!!'
}

async function getTodoList(){

    // 先去缓存里查找，有的话，直接从缓存读取，没有的话，从数据库读取，再存到缓存以便下次请求时使用
    const sql="select * from todolist"

    const result = await execSql(sql);

    const myarray= JSON.parse(JSON.stringify(result))   //RowDataPacket
    return myarray

    //存到缓存，后面从缓存里面获取
}

/*
async function addItem(data){

    const tlist=await getTodoList()

    tlist.push(data)

    const jstr=JSON.stringify(tlist)
    const key="todolist"
    client.set(key,jstr)
}*/


module.exports = {
    getTodoList,addItem,deleteItem,updateItem
}